package com.example.mybatisplus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mybatisplus.mapper.BusinessMapper;
import com.example.mybatisplus.model.domain.Business;
import com.example.mybatisplus.model.dto.PageDTO;
import com.example.mybatisplus.service.BusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business> implements BusinessService {
    @Autowired
    private BusinessMapper businessMapper;

    @Override
    public Page<Business> pageList(Business business, PageDTO dto, boolean sortByDistance, boolean sortByStars) {
        Page<Business> page = new Page<>(dto.getPageNo(), dto.getPageSize());
        QueryWrapper<Business> wrapper = new QueryWrapper<>();

        // 距离筛选
        if (dto.getDistance() != null) {
            wrapper.le("distance", dto.getDistance());
        }

        // 评分筛选
        if (dto.getStars() != null) {
            wrapper.ge("stars", dto.getStars());
        }

        // 设施筛选
        if (dto.getAdditionalFilters() != null && !dto.getAdditionalFilters().isEmpty()) {
            String[] filters = dto.getAdditionalFilters().split(",");
            for (String filter : filters) {
                wrapper.and(wrapper1 -> wrapper1.like("attributes", "\"" + filter + "\":\"True\""));
            }
        }

        // 排序逻辑
        if (sortByDistance) {
            List<Business> list = businessMapper.findnearBusiness();
            int total = list.size();
            int start = (int) ((page.getCurrent() - 1) * page.getSize());
            int end = Math.min(start + (int) page.getSize(), total);
            List<Business> pageList = list.subList(start, end);
            page.setTotal(total);
            page.setRecords(pageList);
        } else if (sortByStars) {
            List<Business> list = businessMapper.findHighScoreBusiness();
            int total = list.size();
            int start = (int) ((page.getCurrent() - 1) * page.getSize());
            int end = Math.min(start + (int) page.getSize(), total);
            List<Business> pageList = list.subList(start, end);
            page.setTotal(total);
            page.setRecords(pageList);
        } else {
            baseMapper.selectPage(page, wrapper);
        }

        return page;
    }
}
